/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.bt

import org.ibiblio.terasaur.user.User
import org.ibiblio.terasaur.bt.Seedbank

class SeedbankService {
    static transactional = true
    boolean _flushTransactions = false // Option for unit testing

    /**
     * Save a seed bank
     *
     * @param Map params
     * @return Map result
     */
    def save(Map params, User user) {
        Map result
        Seedbank seedbank = null
        boolean success = false
        try {
            seedbank = _getSeedbankFromParams(params)
            seedbank.owner = user
            if (seedbank.save(insert:true, flush:_flushTransactions)) {
                success = true
            }
        } catch (Exception e) {
            log.error("Seed bank save exception (" + e.class.name + "): " + e.message)
            success = false
        }

        result = [
            success: success,
            seedbank: seedbank,
        ]
        return result
    }

    protected Seedbank _getSeedbankFromParams(Map params) {
        Seedbank seedbank = new Seedbank(
            peerId: params.peerId,
            ipAddress: params.ipAddress,
            ipPort: params.ipPort,
            name: params.name
            )
        return seedbank
    }

}
